<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft"> </template>
      <template slot="menuRight">
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
          >导出
        </el-button>
      </template>
      <template slot-scope="{}" slot="receiveRpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.receiveRpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="发券商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="核券商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="ticketCodeSearch">
        <select-page
          ref="searchTicketSelect"
          label="ticketName"
          value="ticketCode"
          :select.sync="search.ticketCode"
          url="/ticket/list"
          placeholder-text="核券商户"
          filter-key="searchParam"
        ></select-page>
      </template>
      <!-- <template slot-scope="{ row }" slot="rpiNo">
        <span
          class="haruyuki-color-subjectbluelight cursor-pointer"
          @click="handleMarchantDetails(row)"
          >{{ row.rpiNo }}</span
        >
      </template> -->
    </avue-crud>
    <div class="curd-foter">
      <div class="redFontBox" v-if="isShowCounts">
        发券总数：<span class="redFont">{{
          exhibition(countData.totalCount) || 0.0
        }}</span>
        张
      </div>
      <div class="redFontBox">
        领券总数：<span class="redFont">{{
          exhibition(countData.receiveCount) || 0.0
        }}</span>
        张
      </div>
      <div class="redFontBox">
        已核销总数：<span class="redFont">{{
          exhibition(countData.useCount) || 0.0
        }}</span>
        张
      </div>
      <div class="redFontBox">
        减免金额：<span class="redFont">{{
          exhibition(countData.discountAmount) || 0.0
        }}</span>
        元
      </div>
    </div>
  </basic-container>
</template>

<script>
import {
  getList,
  statistics,
  getExport,
} from "@/api/rb-oem/ticket/ticket_record";
import { mapGetters } from "vuex";
import { downloadFileExcel } from "@/util/util";
import selectPage from "@/components/select-page/select-page";

export default {
  props: {
    ticketCode: {
      type: String,
      required: '',
    },
    isShowCounts: {
      type: Boolean,
      required: false,
    },
  },
  components: {
    selectPage,
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchIndex: 3, //从第三个后隐藏 searchIcon
        searchIcon: true, //显示搜索 展开/隐藏按钮
        // searchLabelWidth:120,
        selection: false,
        // searchMenuSpan: 6,
        columnBtn: false,
        menu: false,
        column: [
          {
            label: "会员ID",
            prop: "memberNo",
            type: "input",
            minWidth: 100,
            searchOrder: 1,
            search: true,
            overHidden: true,
          },
          {
            label: "会员昵称",
            prop: "memberName",
            type: "input",
            minWidth: 100,
            searchOrder: 2,
            search: true,
            overHidden: true,
          },
          {
            label: "发券商户编号",
            searchLabel: "发券商户",
            prop: "receiveRpiNo",
            type: "select",
            searchOrder: 3,
            minWidth: 100,
            search: true,
            overHidden: true,
          },
          {
            label: "发券商户名称",
            prop: "receiveRpiName",
            type: "input",
            minWidth: 100,
            overHidden: true,
          },
          {
            label: "优惠券记录编号",
            prop: "ticketRecordCode",
            type: "input",
            search: true,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "优惠券类型",
            prop: "ticketTypeName",
            type: "input",
            minWidth: 90,
            overHidden: true,
          },
          {
            label: "优惠券类型",
            prop: "ticketType",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=ticket_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择优惠券类型",
                trigger: "blur",
              },
            ],
            hide: true,
          },
          {
            label: "充值类型",
            prop: "rechargeTypeName",
            type: "input",
            minWidth: 90,
            overHidden: true,
          },
          {
            label: "充值类型",
            prop: "rechargeType",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=recharge_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择充值类型",
                trigger: "blur",
              },
            ],
            hide: true,
          },
          {
            label: "发券活动编号",
            searchLabel: "发券活动",
            prop: "ticketCode",
            type: "select",
            search: true,
            minWidth: 100,
            overHidden: true,
          },
          {
            label: "发券活动名称",
            prop: "ticketName",
            type: "input",
            minWidth: 100,
            overHidden: true,
          },
          {
            label: "核券商户编号",
            searchLabel: "核券商户",
            searchOrder: 4,
            prop: "rpiNo",
            type: "select",
            search: true,
            minWidth: 100,
            overHidden: true,
          },
          {
            label: "核券商户名称",
            prop: "rpiName",
            type: "select",
            minWidth: 100,
            overHidden: true,
          },
          {
            label: "优惠券状态",
            prop: "useStatusName",
            type: "input",
            minWidth: 90,
            overHidden: true,
          },
          {
            label: "优惠券状态",
            prop: "useStatus",
            type: "select",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=use_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            rules: [
              {
                required: true,
                message: "请选择充值类型",
                trigger: "blur",
              },
            ],
            hide: true,
          },
          {
            label: "满减金额",
            prop: "discountAmount",
            type: "input",
            minWidth: 90,
            overHidden: true,
          },
          {
            label: "领券日期",
            prop: "createTime",
            type: "input",
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "核券日期",
            prop: "useTime",
            type: "input",
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "领券日期",
            prop: "dateTime",
            type: "datetimerange",
            searchRange: true,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            search: true,
            rules: [
              {
                required: true,
                message: "请选择领券日期",
                trigger: "blur",
              },
            ],
            showColumn: false,
            hide: true,
            display: false,
            searchSpan: 6,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "核券日期",
            prop: "dateUse",
            type: "datetimerange",
            searchRange: true,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            search: true,
            showColumn: false,
            hide: true,
            display: false,
            searchSpan: 6,
            minWidth: 140,
            overHidden: true,
          },
          {
            label: "有效期",
            prop: "useTime",
            type: "input",
            minWidth: 140,
            overHidden: true,
          },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/terminal/terminal/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      countData: {},
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.store_add, false),
        viewBtn: this.vaildData(this.permission.store_view, false),
        delBtn: this.vaildData(this.permission.store_delete, false),
        editBtn: this.vaildData(this.permission.store_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    getColor() {
      return (state) => {
        if (state == "0") {
          return "#F56C6C";
        } else if (state == "1") {
          return "#67C23A";
        }
      };
    },
    getColorStatus() {
      return (state) => {
        if (state == "0") {
          return "#E6A23C";
        } else if (state == "1") {
          return "#67C23A";
        }
      };
    },
    exhibition() {
      return (val) => {
        if (val == "" || val == "-1" || val == "0") {
          return (val = 0);
        } else {
          return val;
        }
      };
    },
  },
  watch: {
    "search.dateTime"(val) {
      if (val) {
        this.search.beginCreateTime = val[0];
        this.search.endCreateTime = val[1];
      } else {
        this.search.beginCreateTime = "";
        this.search.endCreateTime = "";
      }
    },
    "search.dateUse"(val) {
      if (val) {
        this.search.beginUseTime = val[0];
        this.search.endUseTime = val[1];
      } else {
        this.search.beginUseTime = "";
        this.search.endUseTime = "";
      }
    },
  },
  created() {},
  methods: {
    /**
     * @func 详情
     * @desc 点击详情进入详情界面
     * @param {Object} row - 商户信息
     * */
    handleDetail(row) {
      this.$router.push({
        name: "商户详情",
        query: {
          rpiNo: row.rpiNo,
          rpiExStatus: row.rpiExStatus,
        },
      });
    },
    /**
     * @func 商户详情
     * @desc 点击商户编号进入商户详情界面(登记商户)
     * @param {Object} row - 数据信息
     * */
    handleMarchantDetails(row) {
      this.$router.push({
        path: "/rb-oem/posinfo/pos_info_reg_details",
        query: {
          d: this.$crypto.encrypt(
            JSON.stringify({
              rpiNo: row.rpiNo,
            })
          ),
        },
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then((res) => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign({ ticketCode: this.ticketCode || ''  }, params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
      statistics(Object.assign({ ticketCode: this.ticketCode || '' }, params, this.query)).then((res) => {
        this.countData = res.data.data;
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        getExport(this.search).then(
          (res) => {
            this.$message({ type: "success", message: res.data.msg });
          },
          (error) => {
            window.console.log(error);
          }
        );
      });
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-tag--dark.el-tag--success {
  border-color: transparent;
  opacity: 0.8;
}

.line_top {
  border-top: 1px solid #e0eafc;
}

.p-l-20 {
  padding-left: 20px;
}

.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}
.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
</style>
